package com.reflection;

import java.lang.reflect.Constructor;

public class t2_构造方法 {
    public static void main(String[] args) throws Exception {
        //获取Class对象
        Class<?> clazz = Class.forName("com.reflection.Student");

        //1.获取所有公共构造方法
        Constructor<?>[] c1 = clazz.getConstructors();
        for (Constructor<?> c : c1) {
            System.out.println(c);
        }
        //2.获取所有构造方法(包括私有的)
        Constructor<?>[] c2 = clazz.getDeclaredConstructors();
        for (Constructor<?> c : c2) {
            System.out.println(c);
        }
        //3.获取指定的构造方法
        //获取空参构造
        Constructor<?> c3 = clazz.getConstructor();
        Constructor c4 = clazz.getConstructor(String.class);
        System.out.println(c3);
        System.out.println(c4);

        //4.获取指定的构造方法(包括私有的)
        Constructor c5 = clazz.getDeclaredConstructor();
        Constructor<?> c6 = clazz.getDeclaredConstructor(String.class, int.class);
        System.out.println(c5);
        System.out.println(c6);

        //5.调用构造方法创建对象
        //空参
        Student s1 = (Student) c3.newInstance();
        System.out.println(s1);
        //带参
        Student s2 = (Student) c4.newInstance("张三");
        System.out.println(s2);

        //暴力反射创建
        //使用private的私有构造方法
        Constructor<?> c = clazz.getDeclaredConstructor(String.class, int.class);
        c.setAccessible(true);  //临时修改构造方法的访问权限
        Student s = (Student) c.newInstance("王五", 88);
        System.out.println(s);

    }
}
